# -*- coding: utf-8 -*-
# @Time    : 2020/7/1 19:09
# @Author  : lerry-lee
# @Version : 1.0
# @Description:把中文文本翻译成英文，再翻译回中文
import time
import logging
from trans2en_single import main as trans_single_zh_to_en
from trans2zh_single import main as trans_single_en_to_zh

log = logging.getLogger("mylog")


def prepare_log(logger):
    '''
    logging初始化
    '''
    formatter = logging.Formatter(fmt='[%(levelname)s] %(asctime)s [%(filename)s:%(lineno)d]:\t%(message)s')
    console_hdl = logging.StreamHandler()
    console_hdl.setFormatter(formatter)
    logger.addHandler(console_hdl)
    logger.setLevel(logging.DEBUG)
    logger.propagate = False


def run2en(input_file, output_file, start_idx, end_idx):
    '''
    将中文翻译成英文
    :param input_file: 中文文本所在文件，一行含有一句要翻译的句子，位于第二列
    :param output_file: 翻译后的结果，第一列问原句，第二列为英文译文
    :param start_idx: 开始处理的行号，从0开始计数（人类习惯实际从1开始，因此要减1）
    :param end_idx: 停止处理的行号（包括该行）
    '''
    raw_list = []
    res_list = []
    cnt = 0
    with open(input_file, "r", encoding="utf-8")as f:
        for line in f.readlines():
            line = line.strip().split("\t")[1]
            if start_idx <= cnt <= end_idx:
                log.info("正在处理第{}条：\t{}".format(cnt, line))
                raw_res = trans_single_zh_to_en(line)
                raw_list.append(raw_res["src"])
                res_list.append(raw_res["dst"])
                time.sleep(1)

            if cnt > end_idx:
                break
            cnt += 1

    with open(output_file, "w", encoding="utf-8") as f:
        for raw, res in zip(raw_list, res_list):
            f.write(raw + "\t" + res + "\n")


def run2zh(input_file, output_file, start_idx):
    '''
    将英文翻译成中文
    Args:
        input_file:
        output_file:
        start_idx:

    Returns:

    '''
    raw_list = []
    res_list = []
    cnt = start_idx
    with open(input_file, "r", encoding="utf-8")as f:
        for line in f.readlines():
            line = line.strip().split("\t")[1]
            log.info("正在处理第{}条：\t{}".format(cnt, line))
            raw_res = trans_single_en_to_zh(line)
            raw_list.append(raw_res["src"])
            res_list.append(raw_res["dst"])
            time.sleep(1)
            cnt += 1

    with open(output_file, "w", encoding="utf-8") as f:
        for raw, res in zip(raw_list, res_list):
            f.write(raw + "\t" + res + "\n")


if __name__ == '__main__':
    prepare_log(log)
    run2en(input_file="total_data/from3803to4802_total1000.txt", output_file="results/en_from3803to4802_total1000.txt",
           start_idx=0,
           end_idx=999)
    time.sleep(1)
    run2zh(input_file="results/en_from3803to4802_total1000.txt",
           output_file="results/zh_en_from3803to4802_total1000.txt", start_idx=0)
